package frontend.parser.syntaxtree;

import frontend.lexer.TKType;
import frontend.parser.syntaxtree.symbol.NonTerminalSymbol;
import frontend.parser.syntaxtree.symbol.TerminalSymbol;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * blockItem节点
 *
 * @author 杨凯伟
 * @date 2024/10/14
 */
public class BlockNode extends SyntaxNode {
    public List<BlockItemNode> blockItems = new ArrayList<>();//块项集合
    public int blockRLineNum = -1;// } 所在位置

    /**
     * 判断是否包含 return 语句
     *
     * @return boolean
     */
    public boolean isWithoutReturn() {
        if (blockItems.isEmpty()) {
            return true;
        }
        var lastBlockItem = blockItems.get(blockItems.size() - 1);

        return !(lastBlockItem instanceof BlockItemNodeForStmt blockStmt)
                || !(blockStmt.stmt instanceof StmtNodeForReturn);
    }

    @Override
    public void walk(Consumer<TerminalSymbol> terConsumer, Consumer<NonTerminalSymbol> nonTerConsumer) {
        terConsumer.accept(new TerminalSymbol(TKType.LBRACE));

        blockItems.forEach(blockItem -> blockItem.walk(terConsumer, nonTerConsumer));

        terConsumer.accept(new TerminalSymbol(TKType.RBRACE));

        nonTerConsumer.accept(new NonTerminalSymbol(this));
    }

    @Override
    public String getType() {
        return "Block";
    }
}
